package com.hk.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hk.core.PageResult;
import com.hk.core.Result;
import com.hk.domain.Dept;
import com.hk.domain.User;
import com.hk.dto.TransferDto;
import com.hk.dto.useranddeptdto.DeptDTO;
import com.hk.dto.useranddeptdto.UserDTO;
import com.hk.mapper.DeptMapper;
import com.hk.mapper.UserMapper;
import com.hk.service.DeptService;
import com.hk.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private DeptMapper deptMapper;

    /**   条件分页查询*/
    @Override
    public PageResult list(Integer pageNum, Integer pageSize, String userName, String phonenumber, String status, String beginTime, String endTime) {
        int offset = (pageNum - 1) * pageSize;

        List<User> users = userMapper.list(userName, phonenumber, status, beginTime, endTime, offset, pageSize);
        int total = userMapper.countList(userName, phonenumber, status, beginTime, endTime);

        PageResult pageResult = new PageResult();
        pageResult.setCode(200);
        pageResult.setMsg("查询成功");
        pageResult.setTotal(total);
        pageResult.setRows(users);
        return pageResult;
    }

    /**   根据id查询*/
    @Override
    public User getUserById(Integer userId) {
        User user = userMapper.selectById(userId);
        return user;
    }

    /**   新增用户  */
    @Override
    public void addUser(User user) {

        // 设置创建时间和更新时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        userMapper.insertUser(user);
    }

    /**   根据id删除用户信息   */
    @Override
    public void deleteById(Integer userId) {
        userMapper.delete(userId);
    }

    /**   根据id修改用户信息   */
    public void updateUser(User user) {

        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());

        userMapper.updateUserById(user);
    }

    @Override
    public Page<User> pageList(TransferDto transferDto) {
        log.info("何大煜写的条件查询用户");
        Page<User> userPage = new Page<>(transferDto.getPageNum(), transferDto.getPageSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        String userName = transferDto.getUserName();
//        名字判断空字符串和null
        wrapper.eq(userName!=null&&!"".equals(userName),User::getUserName,userName);
//        手机号码判断null
        wrapper.eq(transferDto.getPhonenumber()!=null,User::getPhonenumber,transferDto.getPhonenumber());
//        时间判断空字符串和null
        Map<String, Object> params = transferDto.getParams();
        if (!"".equals(params.get("beginTime"))){
//            解析时间
            LocalDate beginTime = LocalDate.parse(params.get("beginTime").toString());
            LocalDate endTime = LocalDate.parse(params.get("endTime").toString());
            wrapper.between(User::getCreateTime,beginTime,endTime);
        }
//        查询用户
        Page<User> page = userMapper.selectPage(userPage, wrapper);
        return page;


    }



    @Override
    public List<UserDTO> getUserListByDept(Integer deptId) {
        // 1. 查询用户列表
        List<User> users = userMapper.selectByDeptId(deptId);

        // 2. 转换为DTO列表
        return users.stream().map(user -> {
            UserDTO userDTO = new UserDTO();
            // 复制基本属性
            BeanUtils.copyProperties(user, userDTO);

            // 设置部门信息
            if (user.getDeptId() != null) {
                Dept dept = deptMapper.selectById(user.getDeptId());
                DeptDTO deptDTO = new DeptDTO();
                BeanUtils.copyProperties(dept, deptDTO);
                userDTO.setDept(deptDTO);
            }

            // 设置其他属性（根据你的JSON示例）
            userDTO.setRoles(new ArrayList<>());
            userDTO.setAdmin(false);

            return userDTO;
        }).collect(Collectors.toList());
    }
}
